import React, { useEffect, useState } from 'react';
import TRNotification from '@/utils/notification';
import { TJModel, TjStation, TjTable } from '@/pages/ETrade/components';
import styles from './index.less';
import { Button, DatePicker, Input, message, Select, Space, Spin, Tag } from 'antd';
import { useSetState } from 'ahooks';
import { monthFormat, tableStyle } from '../../constant';
import { useTablePipeline } from 'ali-react-table';
import { calculate, timeRangeInsert, timeRangeList } from '../../services';
import moment from 'moment';
import { HttpCode } from '#/utils/contacts';
import { getTimesPoint, judgeIsBeforeMonth } from '../../helper';
import { PeriodPicker } from '../periodPicker/index';

const width = 169;

const { RangePicker } = DatePicker;

const { CheckableTag } = Tag;
const TimePeriodComponent = ({ onClose, province = [], buttonPermissions = [] }) => {
  const [state, setState] = useSetState({
    type: 1, // type为0是编辑 为1是预览,
    spinning: false,
    loading: false,
    provinceId: province?.[0]['provinceId'] || '',
    marketId: province?.[0]['marketId'],
    year: moment().format('YYYY'),
    month: [1],
    dataSource: [],
  });

  const [calculateLoading, setCalculateLoading] = useState(false);

  const [searchParam, setSearchParams] = useSetState({
    date: [moment(), moment()],
    stationIds: [],
  });

  useEffect(() => {
    if (state.type) {
      (async () => {
        await getData();
      })();
    }
  }, [state.month, state.provinceId, state.year, state.type]);

  const getData = async () => {
    setState({
      loading: true,
    });
    const res = await timeRangeList({
      month: state.month[0],
      provinceId: state.provinceId,
      year: state.year,
    });
    let data = res?.data || [];
    data = data.map((i, k) => ({ ...i, key: k }));
    if (res?.statusCode === HttpCode.SUCCESS) {
      setState({
        dataSource: data,
      });
    } else {
      message.error(res.message || '查询失败!');
    }
    setState({
      loading: false,
    });
  };
  const handleCancel = () => {
    onClose();
  };

  const handleChange = (v, checked) => {
    let month = [v];
    if (!state.type) {
      // 编辑时只能选择当月之前的
      if (!judgeIsBeforeMonth(state.year, [v])) {
        if (checked) {
          month = [...state.month, v];
        } else {
          month = state.month.filter((item) => item !== v);
          if (!month.length) {
            return;
          }
        }
      } else {
        month = state.month;
      }
    }
    setState({
      month,
    });
  };

  const changeWeight = (e, v) => {
    const value = e.target.value;
    const arr = state.dataSource.slice();
    arr[v.key]['weight'] = value;
    setState({
      dataSource: arr,
    });
  };

  const changeOrderData = (v, key, rowKey) => {
    const arr = state.dataSource.slice();
    arr[rowKey][key] = v;
    setState({
      dataSource: arr,
    });
  };

  const deleteDataSource = (rowKey) => {
    let data = state.dataSource.slice();
    data.splice(rowKey, 1);
    data = data?.map((i, k) => ({ ...i, key: k }));
    setState({
      dataSource: data,
    });
  };

  const addDataSource = () => {
    let rowKey = state.dataSource.length - 1;
    rowKey = rowKey < 0 ? 0 : rowKey;
    let data = state.dataSource.slice();
    const value = data[rowKey] || {};
    data.push({
      startTime: value.startTime || '0015',
      endTime: value.endTime || '0015',
      weight: 0,
    });
    data = data?.map((i, k) => ({ ...i, key: k }));
    setState({
      dataSource: data,
    });
  };

  const columns = [
    {
      code: 'startTime',
      name: '时间段',
      align: 'center',
      render: (_, record) => {
        if (state.type) {
          return (
            <div>
              {record.startTime} - {record.endTime}
            </div>
          );
        } else {
          const startTimeValue = getTimesPoint(record.startTime);
          const endTimeValue = getTimesPoint(record.endTime);
          return (
            <PeriodPicker
              list={state.dataSource || []}
              startTimeValue={startTimeValue}
              endTimeValue={endTimeValue}
              onChange={(v, key) => changeOrderData(v, key, record.key)}
            />
          );
        }
      },
    },
    {
      code: 'weight',
      name: (
        <div>
          <div>权重</div>
          <div style={{ color: 'rgba(255, 255, 255, 0.6)' }}>(%)</div>
        </div>
      ),
      align: 'center',
      render: (v, record) =>
        state.type ? (
          v
        ) : (
          <Input
            disabled={judgeIsBeforeMonth(state.year, state.month)}
            className={styles.weight_input}
            type={'number'}
            value={v}
            onChange={(e) => changeWeight(e, record)}
          />
        ),
    },
  ];

  const pipeline = useTablePipeline({ components: {} })
    .input({
      dataSource: state.dataSource || [],
      columns: state.type
        ? columns
        : [
            ...columns,
            {
              code: 'key',
              name: '操作',
              align: 'center',
              render: (v, record) => (
                <div>
                  <a
                    style={{ color: 'rgba(255, 92, 92, 1)', marginLeft: 5 }}
                    onClick={() => deleteDataSource(v)}
                  >
                    删除
                  </a>
                </div>
              ),
            },
          ],
    })
    .primaryKey('key');

  const changeType = (v) => {
    if (v) {
      setState({
        month: [1],
      });
    }
    setState({
      type: v,
    });
  };
  const changeProvince = (v, opt) => {
    setState({
      provinceId: opt.provinceId,
      marketId: opt.marketId,
    });
  };

  const changeYear = (v) => {
    setState({
      year: moment(v).format('YYYY'),
    });
  };

  const handleSave = async () => {
    setState({
      spinning: true,
    });
    const res = await timeRangeInsert({
      year: state.year,
      provinceId: state.provinceId,
      monthList: state.month,
      dataList: state.dataSource,
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      changeType(1);
      message.success('保存成功!');
    } else {
      message.error(res.message || '保存失败!');
    }
    setState({
      spinning: false,
    });
  };

  // 计算
  const handleCalculate = async () => {
    setCalculateLoading(true);
    const params = {};
    params.startDate = searchParam?.date?.[0]?.format('YYYYMM') || '';
    params.endDate = searchParam?.date?.[1]?.format('YYYYMM') || '';
    params.stationIds = searchParam.stationIds;
    const res = await calculate(params);
    if (res?.statusCode === HttpCode.SUCCESS) {
      message.success('计算成功!');
    } else {
      message.error(res.message || '获取数据失败!');
    }
    setCalculateLoading(false);
  };

  const changeStationIds = (v) => {
    setSearchParams({
      stationIds: v,
    });
  };

  const changeDate = (v) => {
    setSearchParams({
      date: v,
    });
  };

  return (
    <TJModel
      visible={true}
      onCancel={handleCancel}
      width={400}
      maskClosable={false}
      title={'时间段设置'}
      centered
      footer={null}
    >
      <div className={styles.first_line}>
        <div>
          <div className={styles.label}>交易中心</div>
          <Select
            style={{ width }}
            showSearch={true}
            filterOption={(inp, option) => option.label.includes(inp)}
            options={province}
            onSelect={changeProvince}
            value={state.marketId}
          />
        </div>
        <div>
          <div className={styles.label}>年份</div>
          <DatePicker
            style={{ width }}
            onChange={changeYear}
            picker="year"
            value={moment(state.year)}
            allowClear={false}
          />
        </div>
      </div>
      <div className={styles.month_line}>
        <div>
          <div className={styles.label}>月份</div>
          {Array.from({ length: 12 }).map((_, k) => (
            <CheckableTag
              key={k + 1}
              style={{
                width: 48,
                height: 24,
                textAlign: 'center',
                marginTop: 5,
                marginLeft: k === 0 || k === 6 ? 0 : 3,
              }}
              checked={state.month.indexOf(k + 1) > -1}
              onChange={(checked) => handleChange(k + 1, checked)}
            >
              {k + 1}月
            </CheckableTag>
          ))}
        </div>
      </div>
      <div className={styles.month_line}>
        <div className={styles.last_line}>
          <div className={styles.label}>月份</div>
          <div>
            {state.type ? (
              <a onClick={() => changeType(0)}>编辑</a>
            ) : (
              <Spin spinning={state.spinning}>
                <a onClick={addDataSource}>新增</a>
                <a style={{ marginLeft: 5 }} onClick={handleSave}>
                  保存
                </a>
                <a style={{ marginLeft: 5 }} onClick={() => changeType(1)}>
                  取消
                </a>
              </Spin>
            )}
          </div>
        </div>
        <TjTable
          isLoading={state.loading}
          // style={tableStyle}
          useOuterBorder={true}
          stickyScrollHeight={10}
          useVirtual={{ horizontal: true, vertical: true, header: false }}
          defaultColumnWidth={100}
          {...pipeline.getProps()}
        />
      </div>
      {/*<div>*/}
      {/*    <Space>*/}
      {/*        <TjStation*/}
      {/*            width={width}*/}
      {/*            options={stations}*/}
      {/*            onChange={changeStationIds}*/}
      {/*            value={searchParam.stationIds}*/}
      {/*        />*/}
      {/*        <RangePicker*/}
      {/*            allowClear={false}*/}
      {/*            onChange={changeDate}*/}
      {/*            style={{width: 200}}*/}
      {/*            value={searchParam.date}*/}
      {/*            format={monthFormat}*/}
      {/*            picker="month"*/}
      {/*        />*/}
      {/*        <Button*/}
      {/*            type={'primary'}*/}
      {/*            onClick={handleCalculate}*/}
      {/*            loading={calculateLoading}*/}
      {/*            disabled={!buttonPermissions.find((item) => item.menuCode === 'dayaheadPriceCalculate')}*/}
      {/*        >*/}
      {/*            计算*/}
      {/*        </Button>*/}
      {/*    </Space>*/}
      {/*</div>*/}
    </TJModel>
  );
};

class TimeSettingModal {
  __key__ = '';
  show = (props) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <TimePeriodComponent
            {...props}
            onClose={() => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve();
            }}
          />
        ),
        duration: null,
      });
    });
  };
  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new TimeSettingModal();
